package com.walter.blog.config;

import cn.hutool.json.JSONUtil;
import com.walter.blog.exception.ConfigNotFoundException;
import com.walter.db.mapper.ConfigMapper;
import com.walter.db.pojo.Config;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.annotation.Resource;
import java.util.Properties;

/**
 * @author: wuchenxi
 * @date: 2020/7/3 16:48:48
 */
@Slf4j
@Configuration
public class MailConfig {

    public static String username;

    @Resource
    private ConfigMapper configMapper;

    @Bean
    public JavaMailSender javaMailSender() {

       Config config = configMapper.selectByType(1);
       if (config == null) {
           throw new ConfigNotFoundException(1);
       }

        Mail mail = JSONUtil.toBean(config.getContent(), Mail.class);

        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setPassword(mail.getPassword());
        javaMailSender.setHost("smtp.qq.com");
        javaMailSender.setPort(465);
        javaMailSender.setUsername(mail.getUsername());
        javaMailSender.setDefaultEncoding("UTF-8");

        Properties javaMailProperties = new Properties();
        javaMailProperties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        javaMailProperties.setProperty("mail.smtp.starttls.enable", "true");
        javaMailSender.setJavaMailProperties(javaMailProperties);

        MailConfig.username = mail.username;
        log.info("邮箱配置加载完成！！！");
        return javaMailSender;
    }

    @Data
    static class Mail {
        private String username;

        private String password;
    }
}
